<script setup lang="ts">
import {fileUploadAPI} from "~/api/fileUpload"
import {compressImageTo200KB} from "~/utils/imgZip"
import { useImageCache } from '~/composables/useImageCache'

const props = defineProps({
  uploadLength:{
    type: Number,
    default: 1
  }
})

const emits = defineEmits(['fileList'])

const fileList = ref([])
const { getCoverImage } = useImageCache()

// 文件上传
const fileInput = ref(null)
const fileUpload = async (e:any)=>{
  const file = e.target.files[0]
  const imgZip = await compressImageTo200KB(file)
  const formParams = new FormData()
  formParams.append('file', imgZip)
  const {data} = await fileUploadAPI(formParams)
  const ossId = data.ossId
  fileList.value.push(ossId)
  fileInput.value.value = ''
  emits('fileList', toRaw(fileList.value))
}
const delUploadImg = (index:number)=>{
  fileList.value.splice(index, 1)
  emits('fileList', toRaw(fileList.value))
}
</script>

<template>
  <div>
    <p class="upload">
							<span class="upload-img" v-for="(item, index) of fileList" :key="item">
                <img class="img" :src="getCoverImage(item)" alt="" />
                <img @click="delUploadImg(index)" class="del" src="~/assets/img-del-icon.png" alt="">
              </span>
      <span class="upload-add" v-if="fileList.length < props.uploadLength">
                  <img src="~/assets/file-add.png" alt="">
                  <input ref="fileInput" type="file" accept="image/png, image/jpeg" @input="fileUpload">
                </span>
    </p>
  </div>
</template>

<style scoped lang="scss">
.upload{
  display: flex;
  .upload-img{
    width: 50px;
    height: 50px;
    margin-right: 12px;
    border-radius: 12px;
    overflow: hidden;
    position: relative;
    .img{
      height: 100%;
    }
    .del{
      position: absolute;
      top: 2px;
      right: 2px;
      width: 16px;
      height: 16px;
      cursor: pointer;
      transition: all 0.3s;
      &:hover{
        transform: scale(1.4);
      }
    }
  }
  .upload-add{
    flex: 0 0 50px;
    height: 50px;
    position: relative;
    img{
      width: 100%;
      height: 100%;
    }
    input{
      position: absolute;
      top:0;
      left: 0;
      width: 100%;
      height: 100%;
      opacity: 0;
    }
  }
}
</style>